//
//  QuickCardChooseRoomController.m
//  QRMaster
//
//  Created by myApple on 16/5/30.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "QuickCardChooseRoomController.h"
#import "TotalCardCell.h"
#import "RequestNetWork.h"
#import "RoomCardDataProcess.h"
#import "CardInfoModel.h"
#import "RoomCardDataProcess.h"
#import "ChineseInclude.h"
#import "ZYPinYinSearch.h"

@interface QuickCardChooseRoomController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    UITableView * cardTableView;
    __block NSMutableArray * displayArray;
    __block NSMutableArray * totalArray;
    UIImageView * submitImageView;
    UILabel * submitLabel;
    UIButton * backBtn;
    RoomCardDataProcess * dataProcess;
    UISearchBar * roomCardSearchBar;
    NSString * selectRoomId;
}

@end

@implementation QuickCardChooseRoomController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"roomInfo", nil);
    displayArray = [[NSMutableArray alloc]init];
    totalArray = [[NSMutableArray alloc]init];
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    dataProcess = [[RoomCardDataProcess alloc]init];
    [self prepareSearchBar];
    [self prepareNavBtn];
    [self prepareTableView];
    [self initData];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    submitImageView.hidden = NO;
    backBtn.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    submitImageView.hidden = YES;
    backBtn.hidden = YES;
}

-(void)setRoomId:(NSString *)roomId
{
    _roomId = roomId;
    selectRoomId = roomId;
}

-(void)prepareNavBtn
{
    submitImageView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH - 66, 2, 50, 40)];
    submitImageView.userInteractionEnabled = NO;
    UITapGestureRecognizer * submitTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(makeSure)];
    [submitImageView addGestureRecognizer:submitTap];
    [self.navigationController.navigationBar addSubview:submitImageView];
    
    submitLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 50, 20)];
    submitLabel.text = NSLocalizedString(@"authenSubmit",@"完成");
    submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
    submitLabel.font = [UIFont systemFontOfSize:15.0];
    submitLabel.textAlignment = NSTextAlignmentRight;
    [submitImageView addSubview:submitLabel];
    
    float x = 0;
    float y = 0;
    float width = 56;
    float height = 40;
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [backBtn addTarget:self action:@selector(userBack) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:backBtn];
}

#pragma mark - 搜索框
- (void)prepareSearchBar{
    roomCardSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 40)];
    roomCardSearchBar.backgroundColor = UIColorFromRGB(0xebebeb);
    roomCardSearchBar.barStyle = UIBarStyleDefault;
    roomCardSearchBar.placeholder = NSLocalizedString(@"cardName", nil);
    roomCardSearchBar.delegate = self;
    for(UIView *view in  [[[roomCardSearchBar subviews] objectAtIndex:0] subviews]) {
        if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        {
            [view removeFromSuperview];
            view.backgroundColor = [UIColor clearColor];
            break;
        }
    }
    [self.view addSubview:roomCardSearchBar];
}

#pragma mark - searchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
    for(UIView *view in  [[[roomCardSearchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[UIButton class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:NSLocalizedString(@"alterCancel", nil) forState:UIControlStateNormal];
            [cancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        if ([view isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
            
        {
            
            [view removeFromSuperview];
            view.backgroundColor = [UIColor clearColor];
            break;
            
        }
    }
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    [displayArray removeAllObjects];
    if(![searchText isEqualToString:@""]){
        if (![ChineseInclude isIncludeChineseInString:searchText])
        {
            displayArray = [NSMutableArray arrayWithArray: [ZYPinYinSearch searchWithOriginalArray:totalArray andSearchText:searchText andSearchByPropertyName:@"roomName"]];
            
        }else{
            for (CardInfoModel * model in totalArray) {
                if (([model.roomName rangeOfString:searchText].location != NSNotFound))
                {
                    [displayArray addObject:model];
                }
            }
        }
        
    }else{
        displayArray = [totalArray mutableCopy];
    }
    [cardTableView reloadData];
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBar.text = @"";
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    displayArray = [totalArray mutableCopy];
    [cardTableView reloadData];
}

#pragma mark - initData
-(void)initData
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    [postDict setValue:TOKEN forKey:@"token"];
    __weak QuickCardChooseRoomController * weakSelf = self;
    [rnk initWithPath:POST(HOTELINFO) params:postDict block:^(id downLoadData, id error)
     {
         [weakSelf stopWaiting];
         NSArray * data = [downLoadData objectForKey:@"data"];
         if (data) {
              displayArray = [dataProcess analysisHouseData:data];
             totalArray = [displayArray mutableCopy];
         }
         else if (error != nil)
         {
             if ([[error objectForKey:@"status"]intValue] == 211)
             {
                 [PromptInfoView showMessage:NSLocalizedString(@"addCommunity", nil)];
             }
             else if([[error objectForKey:@"status"]intValue] != 301)
             {
                 [PromptInfoView showMessage:[error objectForKey:@"info"]];
                 
             }
             if ([[error objectForKey:@"status"]intValue] == 301) {
//                 [self deleteRooms];
//                 [_cardInfoMutArray removeAllObjects];
             }
//             NSMutableDictionary * dict = [OpertionPlist readDataFromPlist];
//             [dict setValue:data forKey:HOUSEINFO];
//             [OpertionPlist writeDataToPlist:dict];
         }
         [cardTableView reloadData];
         
     }];

}


-(void)prepareTableView
{
    cardTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64)];
    cardTableView.backgroundColor = [UIColor clearColor];
    cardTableView.dataSource = self;
    cardTableView.delegate = self;
    cardTableView.tableHeaderView = roomCardSearchBar;
    [self.view addSubview:cardTableView];
    
//    UIView * headerVeiw = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 0.5)];
//    headerVeiw.backgroundColor = [UIColor colorWithRed:0.6961 green:0.6961 blue:0.6961 alpha:1.0];
//    cardTableView.tableHeaderView = headerVeiw;
    UIView * footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 0.5)];
    footerView.backgroundColor = [UIColor colorWithRed:0.6961 green:0.6961 blue:0.6961 alpha:1.0];
    cardTableView.tableFooterView = footerView;
    
    
    //设置分割线间距
    if([cardTableView respondsToSelector:@selector(setSeparatorInset:)]){
        [cardTableView setSeparatorInset:UIEdgeInsetsMake(0, 16, 0, 0)];
    }
    if([cardTableView respondsToSelector:@selector(setLayoutMargins:)]){
        [cardTableView setLayoutMargins:UIEdgeInsetsMake(0, 16, 0, 0)];
    }
    
    [cardTableView registerNib:[UINib nibWithNibName:@"TotalCardCell" bundle:nil] forCellReuseIdentifier:@"totalCardCell"];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return displayArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * ID = @"totalCardCell";
    TotalCardCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    [cardTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"TotalCardCell" owner:nil options:nil] firstObject];
        cell.backgroundColor = [UIColor whiteColor];
    }
    if (displayArray.count > indexPath.row) {
        CardInfoModel * model = displayArray[indexPath.row];
        cell.roomLabel.text = model.roomName;
        cell.floorLabel.text = model.floorName;
        [cell.floorLabel sizeToFit];
        cell.buildLabel.text = model.bulidingName;
        [cell.buildLabel sizeToFit];
        if ([model.roomId isEqualToString:selectRoomId]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CardInfoModel * model = displayArray[indexPath.row];
    selectRoomId = model.roomId;
    [self judgeRoom];
    [tableView reloadData];
}

#pragma mark ----------用户自定义返回键
-(void)userBack
{
    if ([self judgeRoom]) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"shouldSave", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"notSave", nil) otherButtonTitles:NSLocalizedString(@"save", nil), nil];
        [alterView show];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self makeSure];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 判断是否有选中的房间
-(BOOL)judgeRoom
{
    if (![selectRoomId isEqualToString:_roomId]) {
        submitImageView.userInteractionEnabled = YES;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 1);
        return YES;
    }
    else
    {
        submitImageView.userInteractionEnabled = NO;
        submitLabel.textColor = UIColorFromRGBAndA(0x7dc234, 0.5);
        return NO;
    }
}

#pragma mark - 点击确认
-(void)makeSure
{
    for (CardInfoModel * model in displayArray) {
        if ([model.roomId isEqualToString:selectRoomId]) {
            if (_cardInfoBlock) {
                _cardInfoBlock(model);
            }
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
